package com.google.adwords.samples.convert;

import com.google.adwords.samples.disapproved.Constants;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.Logger;

/**
 * SAX Parser that is used to convert XML Reports to CSV
 * @author alecmgo@gmail.com (Alec Go)
 *
 */
public class ReportXmlHandler extends DefaultHandler {
  private static final Logger logger = 
    Logger.getLogger(ReportXmlHandler.class.getName());
  
  private final static String OUTPUT_FILE = "OUTPUT.TSV";
  final private Writer out;

  /**
   * Constructor - initializes an output file, and writes the headers
   * @param dir
   * @throws IOException
   */
  public ReportXmlHandler(File dir) throws IOException {
    out = new FileWriter(dir.getAbsolutePath() + "/" + OUTPUT_FILE);
    out.write(Constants.KEYWORD_REPORT_HEADER_LINE);
    out.flush();
  }  

  /**
   * SAX Handler - prints out all the attributes for <row> elements
   */
  public void startElement(String namespaceUri, String localName,
      String qualifiedName, Attributes attrs) throws SAXException {
    if (qualifiedName.equals("row")) {
      print(XmlToCsvConverter.currentAccount + "\t");
      if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
          String aName = attrs.getLocalName(i); // Attr name
          if ("".equals(aName))
            aName = attrs.getQName(i);
          print(attrs.getValue(i) + "\t");
        }
      }
      print("\n");
    }
  }
  
  /**
   * Outputs the string to a file
   * @param s String to be written
   */  
  private void print(String s) throws SAXException {
    try {
      logger.finest(s);
      out.write(s);
      out.flush();
    } catch(IOException e) {
      //TODO Don't hide the IOException in a SAXException
      throw new SAXException(e);
    }
  }
}
